import chalk from 'chalk';
import mongoose from 'mongoose';
import config from "../config";
import { Slider, Dog, IDogDocument } from "../models"

const initialDB = async (): Promise<any> => {
    try {
        // 默认开始 5个连接池-该库已经继承自动重新功能
        const db = mongoose.connection;
        db.on("error", (e) => {
            console.log(chalk.red("连接出错:", e))
        })
        db.once("open", (e) => {
            console.log(chalk.green("连接数据库成功！"));
        })
        db.on("disconnected", (e) => {
            console.warn(chalk.yellow("断开数据库连接！"));
        })
        db.on("reconnected", (e) => {
            console.log(chalk.green("重新连接数据库成功！"));
        })

        let _mongoose = await mongoose.connect(config.MONGODB_URL, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            serverSelectionTimeoutMS: 5000,// 操作超时5s
        })

        await initialSlider();
        await  initialDogs();
    }
    catch (e) {
        return Promise.reject(e.message);
    }
}

const initialSlider = async () => {
    const sliders = await Slider.find();
    if (sliders.length === 0) {
        const sliders: Array<any> = [
            { url: "/images/sliders/1.jpg" },
            { url: '/images/sliders/2.jpg' },
            { url: '/images/sliders/3.jpg' },
            { url: '/images/sliders/4.jpg' },
            { url: '/images/sliders/5.jpg' }
        ]
        await Slider.insertMany(sliders);
    }
}

const initialDogs = async () => {
    let dogs = await Dog.find();
    if (dogs.length !== 0) return;
    let hashiqi={
        order: 0,
        title: "精品哈士奇",
        video: "/images/dogs/dog.mp4",
        poster: "/images/dogs/hashiqi.jpg",
        url: "/images/dogs/hashiqi.jpg",
        price: "¥299.00元",
        category: "哈士奇", 
    }
    let tianyuanquan={
        order: 0,
        title: "中华田园犬",
        video: "/images/dogs/dog.mp4",
        poster: "/images/dogs/tianyuanquan.jpg",
        url: "/images/dogs/tianyuanquan.jpg",
        price: "¥199.00元",
        category: "田园犬",
    }
    let data=[];
    let index=0;
    for(let j=0;j<20;j++){
        for(let k=0;k<5;k++){
            index++;
            data.push({
                ...hashiqi,
                order:index,
                title:`${index}.`+hashiqi.title
            })
        }
        for(let k=0;k<5;k++){
            index++;
            data.push({
                ...tianyuanquan,
                order:index,
                title:`${index}.`+tianyuanquan.title
            }) 
        }
    }
    console.log("已初始化"+data.length+"条数据");
    await  Dog.insertMany(data);
}

export default {
    initialDB
}